﻿using OpenTK.Graphics.OpenGL4;
using OpenTK.Mathematics;
using System.Drawing;

namespace TrinityEngine
{
    public class SimpleSpriteRenderer : Renderer
    {
        public Sprite sprite
        {
            get { return _sprite; }
            set
            {
                _sprite = value;
                _material.SetTexture(_sprite.texture);
            }
        }
        private Sprite _sprite;

        public Vector2 pivot;

        public Color color;

        public int orderInLayer;

        private readonly static float[] _VertexData = new float[]
        {
            -0.5f, -0.5f, 0.0f, 0.0f,
            0.5f, -0.5f, 1.0f, 0.0f,
            0.5f, 0.5f, 1.0f, 1.0f,
            -0.5f, 0.5f, 0.0f, 1.0f
        };

        private readonly static uint[] _indices = new uint[] { 0, 1, 2, 2, 3, 0 };

        private VertexArray _va;

        private StaticVertexBuffer _vb;

        private StaticIndexBuffer _ib;

        private SimpleSpriteMaterial _material;

        public SimpleSpriteRenderer()
        {
            _va = new VertexArray();

            _vb = new StaticVertexBuffer(_VertexData);

            VertexBufferLayout layout = new VertexBufferLayout();
            layout.PushFloat(2);
            layout.PushFloat(2);

            _va.AddBuffer(layout);

            _ib = new StaticIndexBuffer(_indices);

            _material = new SimpleSpriteMaterial();
        }

        protected override void Render()
        {
            _va.Bind();
            _ib.Bind();
            _material.Bind();
            _material.SetUniform(GetMVPMatrix());

            GL.DrawElements(PrimitiveType.Triangles, _ib.GetCount(), DrawElementsType.UnsignedInt, 0);
        }

        private Matrix4 GetMVPMatrix()
        {
            return sprite.imageToUnitMatrix * transform.localToWorldMatrix * Camera.main.worldToCameraMatrix;
        }

        protected override void OnDestroy()
        {
            _va.Dispose();
            _vb.Dispose();
            _ib.Dispose();
            _material.Dispose();
        }
    }
}
